﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Xms.Abp.BackgroundJob;

[BackgroundJobName("注入服务执行任务", nameof(ServiceBackgroundJob))]
public class ServiceBackgroundJob : BackgroundJob<ServiceBackgroundJobArgs>
{
    protected IServiceProvider ServiceProvider { get; }

    public ServiceBackgroundJob(IServiceProvider serviceProvider)
    {
        ServiceProvider = serviceProvider;
    }

    public override async Task ExecuteAsync(ServiceBackgroundJobArgs args, CancellationToken cancellationToken = default)
    {
        var type = Type.GetType(args.Type, true);
        var service = ServiceProvider.GetRequiredService(type);
        var method = type.GetMethod(args.Method);
        var result = method.Invoke(service, args.Args);
        if (result is Task task) await task;
    }
}
